Option Strict On
Option Explicit On

'Copyright (c) 2007-2010, William Severance, Jr., WESNet Designs
'All rights reserved.

'Redistribution and use in source and binary forms, with or without modification, are permitted
'provided that the following conditions are met:

'Redistributions of source code must retain the above copyright notice, this list of conditions
'and the following disclaimer.

'Redistributions in binary form must reproduce the above copyright notice, this list of conditions
'and the following disclaimer in the documentation and/or other materials provided with the distribution.

'Neither the name of William Severance, Jr. or WESNet Designs may be used to endorse or promote
'products derived from this software without specific prior written permission.

'Disclaimer: THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS
'            OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
'            AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER BE LIABLE
'            FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
'            LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
'            INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
'            OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
'            IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

'Although I will try to answer questions regarding the installation and use of this software when
'such questions are submitted via e-mail to the below address, no promise of further
'support or enhancement is made nor should be assumed.

'Developer Contact Information:
'     William Severance, Jr.
'     WESNet Designs
'     679 Upper Ridge Road
'     Bridgton, ME 04009
'     Phone: 207-647-9375
'     E-Mail: bill@wesnetdesigns.com
'     Website: www.wesnetdesigns.com

Imports Microsoft.VisualBasic
Imports DotNetNuke.Security


Namespace WESNet.DNN.Modules.EPrayer
    Public Class EPrayerModuleBase
        Inherits DotNetNuke.Entities.Modules.PortalModuleBase

#Region "Private Members"

        Private _PageSize As Integer = -1
        Private _CurrentPage As Integer = 0

        Private _RequestID As Integer = -1
        Private _PostID As Integer = -1
        Private _Moderation As String
        Private _PostAction As Enums.PostActions = Enums.PostActions.Undetermined
        Private _ModerationAction As Enums.ModerationActions = Enums.ModerationActions.None
        Private _UserInfo As WESNet.DNN.Modules.EPrayer.UserInfo = Nothing
        Private _IsAdministrator As Integer = -2
        Private _CanPost As Integer = -1
        Private _CanModerate As Integer = -1
        Private _MyConfiguration As WESNet.DNN.Modules.EPrayer.Configuration

        Private _UserInfoInitialized As Boolean = False

#End Region

#Region "Public Properties"

        Public Overridable Property PageSize() As Integer
            Get
                Return _PageSize
            End Get
            Set(ByVal value As Integer)
                _PageSize = value
            End Set
        End Property

        Public Overridable Property CurrentPage() As Integer
            Get
                Return _CurrentPage
            End Get
            Set(ByVal value As Integer)
                _CurrentPage = value
            End Set
        End Property

        Public Property RequestID() As Integer
            Get
                Return _RequestID
            End Get
            Set(ByVal value As Integer)
                _RequestID = value
            End Set
        End Property

        Public Property PostID() As Integer
            Get
                Return _PostID
            End Get
            Set(ByVal value As Integer)
                _PostID = value
            End Set
        End Property

        Public Property Moderation() As String
            Get
                Return _Moderation
            End Get
            Set(ByVal value As String)
                _Moderation = value
            End Set
        End Property

        Public Property PostAction() As Enums.PostActions
            Get
                Return _PostAction
            End Get
            Set(ByVal value As Enums.PostActions)
                _PostAction = value
            End Set
        End Property

        Public Property ModerationAction() As Enums.ModerationActions
            Get
                Return _ModerationAction
            End Get
            Set(ByVal value As Enums.ModerationActions)
                _ModerationAction = value
            End Set
        End Property

        Public Property ReturnUrl() As String
            Get
                If ViewState("ReturnUrl") Is Nothing Then
                    Return NavigateURL()
                Else
                    Return CType(ViewState("ReturnUrl"), String)
                End If
            End Get
            Set(ByVal value As String)
                ViewState("ReturnUrl") = value
            End Set
        End Property

        Public Shadows ReadOnly Property UserInfo() As WESNet.DNN.Modules.EPrayer.UserInfo
            Get
                If _UserInfo Is Nothing Then
                    Dim epc As New EPrayerController
                    _UserInfo = epc.GetUser(ModuleId, UserId)
                    _UserInfoInitialized = True
                End If
                Return _UserInfo
            End Get
        End Property

        Public ReadOnly Property IsUserInfoInitialized() As Boolean
            Get
                Return _UserInfoInitialized
            End Get
        End Property

        'Uses a tri-state check to avoid repeated calls to IsInRoles
        Public ReadOnly Property IsAdministrator() As Boolean
            Get
                If _IsAdministrator = -2 Then
                    '_IsAdministrator = Convert.ToInt16(PortalSecurity.IsInRoles(PortalSettings.ActiveTab.AdministratorRoles) _
                    '                                     Or PortalSecurity.IsInRoles(PortalSettings.AdministratorRoleName))
                    _IsAdministrator = Convert.ToInt16(MyBase.ModuleContext.EditMode Or PortalSecurity.IsInRoles(PortalSettings.AdministratorRoleName))
                End If
                Return Convert.ToBoolean(_IsAdministrator)
            End Get
        End Property

        Public ReadOnly Property IsAnonymous() As Boolean
            Get
                Return UserId = -1
            End Get
        End Property

        Public ReadOnly Property IsUnderBan() As Boolean
            Get
                Return (UserInfo.IsBanned AndAlso (UserInfo.BannedUntilDate > Now()))
            End Get
        End Property

        Public ReadOnly Property CanPost() As Boolean
            Get
                If _CanPost = -1 Then
                    If IsAdministrator Or (HasPostPermission() And Not IsUnderBan()) Then
                        _CanPost = 1
                    Else
                        _CanPost = 0
                    End If
                End If
                'End If
                Return _CanPost = 1
            End Get
        End Property

        Public ReadOnly Property CanModerate() As Boolean
            Get
                If _CanModerate = -1 Then
                    If IsAnonymous Then
                        _CanModerate = 0
                    Else
                        If IsAdministrator OrElse (HasModeratePermission() AndAlso UserInfo.IsModerator) Then
                            _CanModerate = 1
                        Else
                            _CanModerate = 0
                        End If
                    End If
                End If
                Return _CanModerate = 1
            End Get
        End Property

        Public ReadOnly Property CanEdit(ByVal CreatedByUserId As Integer) As Boolean
            Get
                Return (Not IsAnonymous) AndAlso (CanModerate OrElse (MyConfiguration.AllowOwnPostEditing AndAlso (HasPostPermission() AndAlso (UserId = CreatedByUserId) AndAlso UserInfo.IsTrusted AndAlso Not IsUnderBan())))
            End Get
        End Property

        Public ReadOnly Property CanDelete(ByVal CreatedByUserId As Integer) As Boolean
            Get
                Return (Not IsAnonymous) AndAlso (CanModerate OrElse (MyConfiguration.AllowOwnPostDeletion AndAlso (HasPostPermission() AndAlso (UserId = CreatedByUserId) AndAlso UserInfo.IsTrusted AndAlso Not IsUnderBan())))
            End Get
        End Property

        Public Function HasModeratePermission() As Boolean
            'Return HasModulePermission(Permission.ModerateKey)
            Return Permissions.ModulePermissionController.HasModulePermission(ModuleConfiguration.ModulePermissions, Permission.ModerateKey)
        End Function

        Public Function HasPostPermission() As Boolean
            'Return HasModulePermission(Permission.PostKey)
            Return Permissions.ModulePermissionController.HasModulePermission(ModuleConfiguration.ModulePermissions, Permission.PostKey)
        End Function

        <System.ComponentModel.Category("Action")> Public ReadOnly Property MyConfiguration() As WESNet.DNN.Modules.EPrayer.Configuration
            Get
                If _MyConfiguration Is Nothing Then
                    Dim CacheKey As String = String.Format(Consts.ConfigurationCacheKey, ModuleId)
                    Dim obj As Object = DataCache.GetCache(CacheKey)
                    If obj Is Nothing Or Consts.ConfigurationCacheDuration = 0 Then
                        _MyConfiguration = New Configuration(ModuleId)
                        DataCache.SetCache(CacheKey, _MyConfiguration, New TimeSpan(0, 0, Consts.ConfigurationCacheDuration))
                    Else
                        _MyConfiguration = CType(obj, WESNet.DNN.Modules.EPrayer.Configuration)
                    End If
                End If
                Return _MyConfiguration
            End Get
        End Property

#End Region

#Region "Public and Protected Methods"

        Public Function PostURL(ByVal PostID As Integer, ByVal AppendReturnUrl As Boolean) As String
            If AppendReturnUrl Then
                Return NavigateURL(TabId, "", "postid=" & PostID.ToString, "returnurl=" & Request.RawUrl)
            Else
                Return NavigateURL(TabId, "", "postid=" & PostID.ToString)
            End If
        End Function

        Public Sub InvalidateConfiguration()
            DataCache.RemoveCache(String.Format(Consts.ConfigurationCacheKey, ModuleId))
            _MyConfiguration = Nothing
        End Sub

        Public Function ConvertToUserTime(ByVal dt As DateTime) As DateTime
            If Not UserId = -1 AndAlso Not UserInfo Is Nothing AndAlso Not UserInfo.Profile Is Nothing Then
                Dim ps As PortalSettings = PortalController.GetCurrentPortalSettings
                Dim offset As Double = Convert.ToDouble(UserInfo.Profile.TimeZone - ps.TimeZoneOffset)
                Return dt.AddMinutes(offset)
            Else
                Return dt
            End If
        End Function

        Public Function FormatCategory(ByVal Category As String, ByVal Visible As Boolean) As String
            If Visible Then
                Return "&nbsp;<span class=""Normal"">(" & Category & ")</span>"
            Else
                Return String.Empty
            End If
        End Function

        Public Function FormatSubmittedBy(ByVal CreatedByUser As String, ByVal SubmittedFor As String, ByVal Relationship As String, ByVal ShowRelationship As Boolean, ByVal CreatedDate As DateTime) As String
            Dim sb As New StringBuilder
            Dim Template As String = LocalizeSharedResource("SubmittedBy")
            Dim s() As String = Template.Split("|"c)
            If CreatedByUser = String.Empty Then
                sb.AppendFormat(s(0), LocalizeSharedResource("Anonymous"))
            Else
                sb.AppendFormat(s(0), CreatedByUser)
            End If
            If Not String.IsNullOrEmpty(SubmittedFor) Then sb.AppendFormat(s(1), SubmittedFor)
            If ShowRelationship Then sb.AppendFormat(s(2), Relationship)
            sb.AppendFormat(s(3), ConvertToUserTime(CreatedDate))
            Return sb.ToString
        End Function

        Public Function FormatLastPostDate(ByVal dt As DateTime) As String
            Dim Str As String
            If dt = Null.NullDate Then
                Str = String.Empty
            Else
                Str = "(" & LocalizeSharedResource("Most_Recent") & ": " & ConvertToUserTime(dt).ToShortDateString & ")"
            End If
            Return Str
        End Function

        Public Function FormatViews(ByVal n As Integer) As String
            If MyConfiguration.TrackViews Then
                Return LocalizeSharedResource("Times_Viewed") & ": " & n.ToString & "&nbsp;&nbsp;&nbsp;"
            Else
                Return String.Empty
            End If
        End Function

        Public Function FormatUpdates(ByVal n As Integer, ByVal dt As DateTime) As String
            Dim Str As String
            If n = 0 Then
                Str = LocalizeSharedResource("No_Updates")
            ElseIf n = 1 Then
                Str = n.ToString & " " & LocalizeSharedResource("Update") & " " & FormatLastPostDate(dt)
            Else
                Str = n.ToString & " " & LocalizeSharedResource("Updates") & " " & FormatLastPostDate(dt)
            End If

            Return Str
        End Function

        Public Function FormatPrayerOrPraise(ByVal IsPraise As Boolean) As String
            Return Utilities.FormatPrayerOrPraise(IsPraise, MyConfiguration.LocalSharedResourceFile)
        End Function

        Public Function RequestTypeImageUrl(ByVal IsPraise As Boolean) As String
            If IsPraise Then
                Return MyConfiguration.ModulePath & "images/Praise.gif"
            Else
                Return MyConfiguration.ModulePath & "images/Prayer.gif"
            End If
        End Function

        Public Function UpdateImageUrl(ByVal StatusID As Integer) As String
            Return MyConfiguration.ModulePath & "images/update" & StatusID.ToString("00") & ".gif"
        End Function

        Public Function ImageUrl(ByVal IsPraise As Boolean, ByVal StatusID As Integer, ByVal IsUpdate As Boolean) As String
            If IsUpdate Then
                Return UpdateImageUrl(StatusID)
            Else
                Return RequestTypeImageUrl(IsPraise)
            End If
        End Function

        Public Function Localize(ByVal s As String) As String
            Return Localization.GetString(s, Me.LocalResourceFile)
        End Function

        Public Function LocalizeSharedResource(ByVal s As String) As String
            Return Localization.GetString(s, MyConfiguration.LocalSharedResourceFile)
        End Function

        Protected Sub SetActions()
            If PostID = -1 Then
                If RequestID = -1 Then
                    _PostAction = Enums.PostActions.NewRequest
                Else
                    _PostAction = Enums.PostActions.NewUpdate
                End If
            Else
                If PostID = RequestID Then
                    _PostAction = Enums.PostActions.EditRequest
                Else
                    _PostAction = Enums.PostActions.EditUpdate
                End If
            End If

            If MyConfiguration.EnableModeration Then
                If Not Moderation Is Nothing AndAlso CanModerate Then
                    Select Case Moderation
                        Case "editapprove"
                            _ModerationAction = Enums.ModerationActions.EditApprove
                        Case "approve"
                            _ModerationAction = Enums.ModerationActions.EditApprove
                        Case "reject"
                            _ModerationAction = Enums.ModerationActions.Reject
                        Case "delete"
                            _ModerationAction = Enums.ModerationActions.Delete
                    End Select
                Else
                    If UserInfo.IsTrusted Then
                        _ModerationAction = Enums.ModerationActions.None
                    Else
                        _ModerationAction = Enums.ModerationActions.Submit
                    End If
                End If
            End If
        End Sub

        Protected Sub PopulatePageSizes(ByVal ddlControl As DropDownList, ByVal RequestedPageSize As Integer)
            If RequestedPageSize < 0 Then RequestedPageSize = 0
            ddlControl.Items.Clear()
            ddlControl.Items.Add(New ListItem(LocalizeSharedResource("Disable_Paging"), "0"))
            For i As Integer = 5 To 50 Step 5
                ddlControl.Items.Add(New ListItem(i.ToString))
            Next
            If RequestedPageSize > 0 Then
                Dim li As New ListItem(RequestedPageSize.ToString)
                If Not ddlControl.Items.Contains(li) Then
                    Dim index As Integer = (RequestedPageSize \ 5) + 1
                    ddlControl.Items.Insert(index, li)
                End If
            End If
        End Sub

#End Region

        Private Sub Page_Init(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Init
            'Initialize the EPrayer UserInfo object
            If _UserInfo Is Nothing Then
                Dim epc As New EPrayerController
                _UserInfo = epc.GetUser(ModuleId, UserId)
            End If

            If Not Request.QueryString("returnurl") Is Nothing Then
                ReturnUrl = Request.QueryString("returnurl")
            End If
        End Sub
    End Class
End Namespace
